//
//  ContentViewController.swift
//  MultipleInfoShow
//
//  Created by iOS Developer on 2017/4/25.
//  Copyright © 2017年 ss. All rights reserved.
//

import UIKit
import CoreData

enum RecordContent {
    case imageContent(ImageContent)
    case textContent(TextContent)
    
    var date: Date {
        switch self {
        case .imageContent(let ic):
            return ic.date! as Date
        case .textContent(let tc):
            return tc.date! as Date
        }
    }
}
class ContentViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,UIPopoverPresentationControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate,CustomTextStyleDelegate {
    var recordContents = [RecordContent]()
    
    var belongRecord: Record!
    
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var userInput: UITextView!
    var modifyStyle: (String, CGFloat, UIColor)?
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.estimatedRowHeight = 50
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.delegate = self
        tableView.dataSource = self
        getDateFromRecord()
        userInput.text = "输入..."
    }
    private func getDateFromRecord(){
        recordContents.removeAll()
        if let imges = belongRecord.images?.allObjects as? [ImageContent] {
            for i in imges {
                recordContents.append(RecordContent.imageContent(i))
            }
        }
        if let texts = belongRecord.texts?.allObjects as? [TextContent] {
            for t in texts {
                recordContents.append(RecordContent.textContent(t))
            }
        }
        recordContents.sort{
            $0.date < $1.date
        }
        tableView.reloadData()
        
    }
    
    @IBAction func addText(_ sender: Any) {
        if userInput.text.trimmingCharacters(in: .whitespaces).isEmpty {
            let alert = UIAlertController(title: "提示", message: "请输入内容", preferredStyle: .alert)
            self.present(alert, animated: true) {
                alert.dismiss(animated: true)
            }
            return
        }
        let newText = TextContent(context: AppDelegate.viewContext)
        newText.content = userInput.text
        newText.fontFamily = "PingFang SC"
        newText.textSize = 17
        newText.textColor = UIColor.black
        if let modify = modifyStyle {
            newText.fontFamily = modify.0
            newText.textSize = Float(modify.1)
            newText.textColor = modify.2
        }
        newText.record = belongRecord
        newText.date = Date() as NSDate
        do {
            try AppDelegate.viewContext.save()
            userInput.text = "输入..."
            getDateFromRecord()
            modifyStyle = nil
            userInput.font = UIFont(name: "PingFang SC", size: 17)
            userInput.textColor = UIColor.black
            let alert = UIAlertController(title: "提示", message: "添加成功!", preferredStyle: .alert)
            self.present(alert, animated: true) {
                alert.dismiss(animated: true)
            }
            
        }catch {
            NSLog("save new writer exception \(error.localizedDescription)")
            let alert = UIAlertController(title: "提示", message: "保存失败!", preferredStyle: .alert)
            self.present(alert, animated: true) {
                alert.dismiss(animated: true)
            }
        }
    }
    
    @IBAction func addImage(_ sender: Any) {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "从相册选择照片", style: .default, handler: { _ in
            let imgPC = UIImagePickerController()
            imgPC.sourceType = .photoLibrary
            imgPC.delegate = self
            self.present(imgPC, animated: true)
        }))
        alert.addAction(UIAlertAction(title: "拍照", style: .default, handler: { _ in
            let imgPC = UIImagePickerController()
            imgPC.sourceType = .camera
            imgPC.delegate = self
            self.present(imgPC, animated: true)
        }))
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        
        self.present(alert, animated: true)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let newImage = ImageContent(context: AppDelegate.viewContext)
        newImage.img = UIImagePNGRepresentation(info[UIImagePickerControllerOriginalImage] as! UIImage)! as NSData
        newImage.date = Date() as NSDate
        newImage.record = belongRecord
        do {
            try AppDelegate.viewContext.save()
            getDateFromRecord()
            let alert = UIAlertController(title: "提示", message: "添加成功!", preferredStyle: .alert)
            present(alert, animated: true) {
                alert.dismiss(animated: true)
            }
            
        }catch {
            NSLog("save new writer exception \(error.localizedDescription)")
            let alert = UIAlertController(title: "提示", message: "保存失败!", preferredStyle: .alert)
            self.present(alert, animated: true) {
                alert.dismiss(animated: true)
            }
        }
        dismiss(animated: true)
    }
    
    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none
    }
    
    @IBAction func setTextCustom(_ sender: Any) {
        if let pop = storyboard?.instantiateViewController(withIdentifier: "textSettingView") as? TextSettingViewController,let btn = sender as? UIButton {
            pop.modalPresentationStyle = .popover
            pop.popoverPresentationController?.delegate = self
            pop.popoverPresentationController?.sourceView = btn
            pop.popoverPresentationController?.sourceRect = btn.bounds
            pop.preferredContentSize = CGSize(width: pop.preferredContentSize.width, height: 360)
            pop.popoverPresentationController?.permittedArrowDirections = .right
            pop.styleDelegate = self
            present(pop, animated: true)
        }
    }
    
    func giveCustomStyle(fontName: String, sizeOfFont: CGFloat, fontColor: UIColor) {
        userInput.font = UIFont(name: fontName, size: sizeOfFont)
        userInput.textColor = fontColor
        modifyStyle = (fontName, sizeOfFont, fontColor)
    }
    
    @IBAction func cancelInput(_ sender: Any) {
        userInput.endEditing(true)
    }
}

extension ContentViewController {
    
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删 除"
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            switch recordContents[indexPath.row] {
            case .imageContent(let iv):
                AppDelegate.viewContext.delete(iv)
            case .textContent(let tc):
                AppDelegate.viewContext.delete(tc)
            }
            recordContents.remove(at: indexPath.row)
            if recordContents.count < 1 {
                tableView.reloadData()
            }else {
                tableView.deleteRows(at: [indexPath], with: .fade)
            }
            try? AppDelegate.viewContext.save()
        } else if editingStyle == .insert {
            
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if recordContents.count > 0 {
            tableView.backgroundView = .none
            return 1
        } else {
            let messageLabel = UILabel(frame: CGRect(x: 0, y: 0,
                                                     width: view.bounds.size.width,
                                                     height: view.bounds.size.height))
            messageLabel.text = "还没有写内容哦.\n你可以插入图片、输入文字."
            messageLabel.textColor = .darkGray
            messageLabel.numberOfLines = 0
            messageLabel.textAlignment = .center
            tableView.backgroundView = messageLabel;
            return 0
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return recordContents.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let rc = recordContents[indexPath.row]
        switch rc {
        case .imageContent(let ic):
            let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell", for: indexPath)
            (cell.viewWithTag(1) as! UIImageView).image = UIImage(data: ic.img! as Data)
            return cell
        case .textContent(let tc):
            let cell = tableView.dequeueReusableCell(withIdentifier: "textCell", for: indexPath)
            let contentLabel = cell.viewWithTag(1) as! UILabel
            contentLabel.textColor = tc.textColor as! UIColor
            contentLabel.font = UIFont(name: tc.fontFamily!, size: CGFloat(tc.textSize))
            contentLabel.text = tc.content
            return cell
        }
        
    }
}

extension ContentViewController {
    override func viewWillAppear(_ animated: Bool) {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    
    func keyboardWillShow(_ notification: Notification) {
        if userInput.text == "输入..." {
            userInput.text = ""
        }
        let info = notification.userInfo! as NSDictionary
        let keyboardSize = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let keyboardHeight: CGFloat = keyboardSize.height
        UIView.animate(withDuration: 0.25){
            self.view.frame.origin.y = -keyboardHeight
        }
    }
    
    func keyboardWillHide(_ notification: Notification) {
        if self.view.frame.origin.y < 0{
            UIView.animate(withDuration: 0.25, animations: {
                self.view.frame.origin.y = 0
            })
        }
    }
}
